package com.starryx.blog.web;

import com.starryx.blog.NotFoundException;
import com.starryx.blog.service.BlogService;
import com.starryx.blog.service.TagService;
import com.starryx.blog.service.TypeService;
import com.starryx.blog.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @GetMapping("/")
    public String index(Integer page,
                        Model model){
        if (page == null){
            model.addAttribute("page", blogService.listBlog(new Page(1, 10, "update_time desc")));

        }else{
            model.addAttribute("page", blogService.listBlog(new Page(page, 10, "update_time desc")));
        }
        // 展示博客数最多的前 6 个分类
        model.addAttribute("types", typeService.listTypeTop(6));
        // 展示博客数最多的前 10 个标签
        model.addAttribute("tags", tagService.listTagTop(10));
        // 展示最近的 8 篇博客
        model.addAttribute("recommendBlogs", blogService.listRecommendBlogTop(8));

        return "index";
    }

    @PostMapping("/search")
    public String search(Integer page,
                         @RequestParam String query,
                         Model model){

        if (page == null){
            //                                                              在这里加上 % 进行模糊查询
            model.addAttribute("page", blogService.listBlog(query, new Page(1, 10, "update_time desc")));
        }else{
            //                                                              在这里加上 % 进行模糊查询
            model.addAttribute("page", blogService.listBlog(query, new Page(page, 10, "update_time desc")));
        }
        model.addAttribute("query", query);
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model){
        model.addAttribute("blog", blogService.getAndConvert(id));
        return "blog";
    }
}
